package com.tools.handler.analysis;

import com.tools.common.result.Result;
import com.tools.handler.StepHandler;
import com.tools.pojo.test.AnalysisRule;
import com.tools.pojo.workflow.bo.StepContext;
import com.tools.service.test.AnalysisRuleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class MedicalRuleConfigStepHandler implements StepHandler {

    private static final String STEP_CODE = "RULE_CONFIG";
    private final AnalysisRuleService analysisRuleService;

    @Override
    public String getStepCode() {
        return STEP_CODE;
    }

    @Override
    public Result<?> execute(StepContext context) {
        try {
            log.info("开始执行医疗规则配置获取步骤，流程实例ID: {}", context.getFlowInstanceId());

            // 从上下文中获取规则ID列表
            List<String> ruleIds = context.getContextData("ruleIds", List.class);
            if (ruleIds == null || ruleIds.isEmpty()) {
                log.warn("未找到规则ID列表，使用所有启用规则");
                ruleIds = new ArrayList<>();
            }

            // 根据规则ID获取规则配置
            List<AnalysisRule> rules;
            if (ruleIds.isEmpty()) {
                // 如果没有指定规则ID，获取所有启用规则
                rules = analysisRuleService.getEnabledRules();
            } else {
                // 根据规则UUID获取规则
                rules = analysisRuleService.getRulesByUuids(ruleIds);
            }

            // 将规则存入上下文
            context.putContextData("analysisRules", rules);
            context.putContextData("requestedRuleIds", ruleIds);
            context.putContextData("actualRuleCount", rules.size());

            log.info("医疗规则配置获取步骤执行成功，请求规则数: {}, 实际获取规则数: {}",
                    ruleIds.size(), rules.size());

            return Result.success("医疗规则配置获取成功", rules.size());

        } catch (Exception e) {
            log.error("医疗规则配置获取步骤执行失败", e);
            return Result.fail("医疗规则配置获取失败: " + e.getMessage());
        }
    }

}
